package com.itcast.test;

import io.jsonwebtoken.*;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘付磊
 * @date 2021/11/11 0011
 */
public class Jwttest {
    @Test
    public void testToken(){
        //生成token
        // 1.准备数据
        Map map = new HashMap();
        map.put("id",1);
        map.put("mobile","15307395915");
        long now = System.currentTimeMillis();
        //2.使用JWT工具类生成token
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, "itcast")//指定加密算法
                .setClaims(map) //写入数据
                .setExpiration(new Date(now + 50000))//失效时间
                .compact();
        System.out.println(token);
    }
    //解析token
    /*
    * SignatureException:token不合法
    * ExpiredJwtException:token 已过期*/
    @Test
    public void tokenParser(){
        String token ="eyJhbGciOiJIUzUxMiJ9.eyJtb2JpbGUiOiIxNTMwNzM5NTkxNSIsImlkIjoxLCJleHAiOjE2MzY2MjA5OTN9.nd3rCfKrEFAWOjj00waZLanpWYXxK-WRUolGYnaQKf-6_UDeGJuSMQ76v4meFRJPcrlebLije9-Z1WvzbsKPSw";
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("itcast")
                    .parseClaimsJws(token)
                    .getBody();
            Object id = claims.get("id");
            Object mobile = claims.get("mobile");
            System.out.println(id +"---"+ mobile);
        }catch (SignatureException e){
            System.out.println("token不合法");
        }catch (ExpiredJwtException e){
            System.out.println("token已过期");
        }
    }
}
